import sys
import numpy as np
from pylab import *
from matplotlib.widgets import Slider, Button, RadioButtons
import readchn
axcolor = 'lightgoldenrodyellow'
data_dir = sys.argv[1]

A = readchn.esc_run(run_path=sys.argv[1])
#A.crop_data(100,400)
fig = figure(figsize=(10,6),dpi=100)
ax = fig.add_subplot(111)
subplots_adjust(left=0.25, bottom=0.25)
ax.plot(A.sum_spec,'b')

#FindPeaks
ax_bpeak = axes([0.025, 0.55, 0.1, 0.05])
bPeak = Button(ax_bpeak,'Find Peaks', color='0.85', hovercolor='0.95')
def FindPeaks(event):
    A.initial_find_peaks()
    A.smart_guess_peaks()
    ymax = ax.get_ybound()[1]
    for peak in A.smart_peaks.values():
        ax.vlines(peak,0,ymax,'g')
    ax.set_ybound([0,ymax])
    draw()
    bFit.active=True
bPeak.on_clicked(FindPeaks)

#FitButton
ax_bfit = axes([0.025,0.45,0.1,0.05])
bFit = Button(ax_bfit,'Do Fit',color='0.85',hovercolor='0.95')
bFit.active=False
def FitPeaks(event):
    A.smart_fit_peaks()
    X = np.arange(0,A.sum_spec.size)
    Y = A.multi_peak_spec(A.smart_parameters)
    ax.plot(X,Y,'r')
    bPeak.active = False
    bFit.active = False
    draw()
bFit.on_clicked(FitPeaks)


rax = axes([0.025, 0.75, 0.15, 0.15], axisbg=axcolor)
radio = RadioButtons(rax, ('Sum', 'Heat_Total', 'Heat_Ind'), active=0)

def plot_type(label):
    if label == 'Heat_Total':
        ax.cla()
        ax.imshow(A.data, interpolation='nearest', aspect='auto')
        draw()
        bPeak.active = False

        bFit.active = False
    if label == 'Heat_Ind':
        ax.cla()
        ax.imshow(A.idata, interpolation='nearest', aspect='auto')
        draw()
        bPeak.active = False
        bFit.active = False
        bPeak.drawon=False
        draw()
    if label == 'Sum':
        bPeak.active = True
        bFit.active = True
        ax.cla()
        ax.plot(A.sum_spec,'b')
        if ax.yaxis_inverted()==True: ax.invert_yaxis()
        draw()

        

        

radio.on_clicked(plot_type)

show()
